package com.consumer.handsome.exception;



import com.consumer.handsome.response.BaseResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.security.SignatureException;
import java.util.Iterator;
import java.util.List;


@RestControllerAdvice
@Slf4j
public class GlobalException {

    /**
     * 业务异常捕捉处理
     *
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = BussinessException.class)
    public BaseResponse bizExceptionHandler(BussinessException e) {
        log.error("业务异常{}", e.getMsg(), e);
        return new BaseResponse(Integer.parseInt(e.getCode()), e.getMsg());
    }

    /**
     * 捕捉spring的字段校验异常
     *
     * @param exception
     * @return
     */
    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<ErrorInfo> validErrorHandler(MethodArgumentNotValidException exception) {
        // 获取异常信息
        BindingResult exceptions = exception.getBindingResult();
        String errorMsg = "";
        // 判断异常中是否有错误信息，如果存在就使用异常中的消息，否则使用默认消息
        if (exceptions.hasErrors()) {
            List<ObjectError> errors = exceptions.getAllErrors();
            if (!errors.isEmpty()) {
                // 这里列出了全部错误参数，按正常逻辑，只需要第一条错误即可
                FieldError fieldError = (FieldError) errors.get(0);
                errorMsg = fieldError.getDefaultMessage();
            }
        }

        ErrorInfo errorInfo = new ErrorInfo(CommonEnum.FAILURE.getResultCode(), CommonEnum.BODY_NOT_MATCH.getResultMsg() + "," + errorMsg);
        return new ResponseEntity<>(errorInfo, HttpStatus.BAD_REQUEST);
    }


    /**
     * 全局异常捕捉处理
     *
     * @param e
     * @return
     */

    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public ResponseEntity<ErrorInfo> errorHandler(Exception e) {
        ErrorInfo errorInfo = new ErrorInfo(CommonEnum.INTERNAL_SERVER_ERROR.getResultCode(), CommonEnum.INTERNAL_SERVER_ERROR.getResultMsg());
        log.error("系统异常{}", e.getMessage(), e);
        return new ResponseEntity<>(errorInfo, HttpStatus.INTERNAL_SERVER_ERROR);
    }


    /**
     * 入参字段校验异常 Valid
     *
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = BindException.class)
    public ResponseEntity<ErrorInfo> errorHandler(BindException e) {
        BindingResult bindingResult = ((BindException) e).getBindingResult();
        String message = this.buildValidationMessage(bindingResult);
        log.error("BindException==============:{}", message);
        ErrorInfo errorInfo = new ErrorInfo(CommonEnum.FAILURE.getResultCode(), CommonEnum.BODY_NOT_MATCH.getResultMsg() + "," + message);
        return new ResponseEntity<>(errorInfo, HttpStatus.OK);
    }

    private String buildValidationMessage(BindingResult bindingResult) {
        StringBuilder sb = new StringBuilder();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        Iterator var4 = fieldErrors.iterator();

        while (var4.hasNext()) {
            FieldError error = (FieldError) var4.next();
            sb.append("格式").append(":");
            sb.append(error.getDefaultMessage()).append("\n ");
        }
        return sb.toString();
    }

    @ResponseBody
    @ExceptionHandler(value = SignatureException.class)
    public BaseResponse<Object> handle(SignatureException e) {
        log.error("handle-->" + e.getMessage());
        return new BaseResponse<Object>(CommonEnum.TOKEN_ERROR);
    }

}



